<template>
  <div class="apikey-management">
    <a-card :bordered="false">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>🔑 API密钥管理</h2>
        <p>管理您的大模型API密钥配置</p>
      </div>

      <!-- API密钥表格 -->
      <a-table
        :columns="columns"
        :data-source="apiKeyList"
        :pagination="pagination"
        :loading="loading"
        rowKey="id"
        @change="handleTableChange"
      >
        <!-- 模型名称列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'modelName'">
            <a-tag color="blue">{{ record.modelName }}</a-tag>
          </template>
          
          <!-- API Key列 - 脱敏显示 -->
          <template v-if="column.dataIndex === 'apiKey'">
            <div class="api-key-cell">
              <span v-if="!record.showFullKey" class="masked-key">
                {{ maskApiKey(record.apiKey) }}
              </span>
              <span v-else class="full-key">{{ record.apiKey }}</span>
              <a-button 
                type="link" 
                size="small" 
                @click="toggleApiKeyVisibility(record)"
              >
                <template #icon>
                  <EyeOutlined v-if="!record.showFullKey" />
                  <EyeInvisibleOutlined v-else />
                </template>
              </a-button>
            </div>
          </template>

          <!-- 启用状态列 -->
          <template v-if="column.dataIndex === 'isActive'">
            <a-switch 
              :checked="record.isActive === 1"
              :loading="record.updating"
              @change="(checked: boolean) => handleStatusChange(record, checked)"
            />
          </template>
          
          <!-- 操作列 -->
          <template v-if="column.dataIndex === 'action'">
            <span>
              <a @click="handleView(record)">查看</a>
              <a-divider type="vertical" />
              <a @click="handleEdit(record)">编辑</a>
            </span>
          </template>
        </template>
      </a-table>

      <!-- 查看详情弹窗 -->
      <a-modal
        title="🔍 API密钥详情"
        :visible="viewModalVisible"
        :footer="null"
        @cancel="handleViewCancel"
        width="600px"
      >
        <div v-if="currentRecord" class="detail-content">
          <a-descriptions :column="1" bordered>
            <a-descriptions-item label="密钥ID">
              {{ currentRecord.id }}
            </a-descriptions-item>
            <a-descriptions-item label="用户ID">
              {{ currentRecord.userId }}
            </a-descriptions-item>
            <a-descriptions-item label="模型名称">
              <a-tag color="blue">{{ currentRecord.modelName }}</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="模型ID">
              {{ currentRecord.modelId }}
            </a-descriptions-item>
            <a-descriptions-item label="API密钥">
              <div class="api-key-display">
                <a-input-password 
                  :value="currentRecord.apiKey" 
                  readonly 
                  :visible-password="true"
                />
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="启用状态">
              <a-tag :color="currentRecord.isActive === 1 ? 'green' : 'red'">
                {{ currentRecord.isActive === 1 ? '启用' : '禁用' }}
              </a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </a-modal>

      <!-- 编辑弹窗 -->
      <a-modal
        title="✏️ 编辑API密钥"
        :visible="editModalVisible"
        :confirm-loading="confirmLoading"
        @ok="handleSubmit"
        @cancel="handleEditCancel"
        width="500px"
      >
        <a-form 
          :model="editForm" 
          :rules="rules" 
          ref="editFormRef" 
          :label-col="{ span: 6 }" 
          :wrapper-col="{ span: 16 }"
        >
          <a-form-item label="密钥ID">
            <a-input :value="editForm.id" disabled />
          </a-form-item>
          <a-form-item label="API密钥" name="apiKey">
            <a-input-password 
              v-model:value="editForm.apiKey" 
              placeholder="请输入API密钥"
              :auto-size="{ minRows: 2, maxRows: 4 }"
            />
          </a-form-item>
          <a-form-item label="启用状态" name="isActive">
            <a-switch 
              v-model:checked="editForm.isActiveChecked"
              checked-children="启用" 
              un-checked-children="禁用" 
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons-vue'
import type { FormInstance } from 'ant-design-vue'
import { getUserApiKeyPage, getUserApiKeyDetail, updateUserApiKey } from '@/api/userApiKey'
import type { UserApiKey } from '@/types/apikey'

// 扩展UserApiKey类型，添加前端状态
interface ExtendedUserApiKey extends UserApiKey {
  showFullKey?: boolean
  updating?: boolean
}

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '用户ID',
    dataIndex: 'userId',
    key: 'userId',
    width: 120,
  },
  {
    title: '模型名称',
    dataIndex: 'modelName',
    key: 'modelName',
    width: 150,
  },
  {
    title: 'API密钥',
    dataIndex: 'apiKey',
    key: 'apiKey',
    width: 300,
  },
  {
    title: '启用状态',
    dataIndex: 'isActive',
    key: 'isActive',
    width: 100,
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 120,
  }
]

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total: number) => `共 ${total} 条记录`,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '20', '50', '100']
})

// 表单相关
const editFormRef = ref<FormInstance>()
const editForm = reactive<{
  id: number
  apiKey: string
  isActive: number
  isActiveChecked: boolean
}>({
  id: 0,
  apiKey: '',
  isActive: 0,
  isActiveChecked: false
})

// 表单校验规则
const rules = {
  apiKey: [
    { required: true, message: '请输入API密钥', trigger: 'blur' },
    { min: 10, message: 'API密钥长度不能少于10位', trigger: 'blur' }
  ]
}

// 状态变量
const loading = ref<boolean>(false)
const viewModalVisible = ref<boolean>(false)
const editModalVisible = ref<boolean>(false)
const confirmLoading = ref<boolean>(false)
const apiKeyList = ref<ExtendedUserApiKey[]>([])
const currentRecord = ref<UserApiKey | null>(null)

// 获取API密钥列表
const fetchApiKeyList = async () => {
  try {
    loading.value = true
    const res = await getUserApiKeyPage({
      page: pagination.current,
      pageSize: pagination.pageSize
    })
    
    if (res.code === 200 && res.data) {
      apiKeyList.value = res.data.result.map(item => ({
        ...item,
        showFullKey: false,
        updating: false
      }))
      pagination.total = res.data.total
    } else {
      message.error(res.message || '获取API密钥列表失败')
    }
  } catch (error) {
    console.error('获取API密钥列表失败', error)
    message.error('获取API密钥列表失败')
  } finally {
    loading.value = false
  }
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchApiKeyList()
}

// API密钥脱敏显示
const maskApiKey = (apiKey: string): string => {
  if (!apiKey || apiKey.length <= 8) {
    return '***'
  }
  const start = apiKey.substring(0, 4)
  const end = apiKey.substring(apiKey.length - 4)
  return `${start}${'*'.repeat(Math.max(8, apiKey.length - 8))}${end}`
}

// 切换API密钥显示状态
const toggleApiKeyVisibility = (record: ExtendedUserApiKey) => {
  record.showFullKey = !record.showFullKey
}

// 查看详情
const handleView = async (record: UserApiKey) => {
  try {
    const res = await getUserApiKeyDetail(record.id)
    if (res.code === 200 && res.data) {
      currentRecord.value = res.data
      viewModalVisible.value = true
    } else {
      message.error(res.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败', error)
    message.error('获取详情失败')
  }
}

// 关闭查看弹窗
const handleViewCancel = () => {
  viewModalVisible.value = false
  currentRecord.value = null
}

// 编辑
const handleEdit = (record: UserApiKey) => {
  editForm.id = record.id
  editForm.apiKey = record.apiKey
  editForm.isActive = record.isActive
  editForm.isActiveChecked = record.isActive === 1
  editModalVisible.value = true
}

// 关闭编辑弹窗
const handleEditCancel = () => {
  editModalVisible.value = false
  editFormRef.value?.resetFields()
}

// 状态切换
const handleStatusChange = async (record: ExtendedUserApiKey, checked: boolean) => {
  try {
    record.updating = true
    const newStatus = checked ? 1 : 0
    
    const res = await updateUserApiKey({
      id: record.id,
      apiKey: record.apiKey,
      isActive: newStatus
    })
    
    if (res.code === 200) {
      record.isActive = newStatus
      message.success('状态更新成功')
    } else {
      message.error(res.message || '状态更新失败')
    }
  } catch (error) {
    console.error('状态更新失败', error)
    message.error('状态更新失败')
  } finally {
    record.updating = false
  }
}

// 提交编辑
const handleSubmit = async () => {
  try {
    await editFormRef.value?.validate()
    confirmLoading.value = true
    
    const res = await updateUserApiKey({
      id: editForm.id,
      apiKey: editForm.apiKey,
      isActive: editForm.isActiveChecked ? 1 : 0
    })
    
    if (res.code === 200) {
      message.success('更新成功')
      editModalVisible.value = false
      fetchApiKeyList()
    } else {
      message.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新失败', error)
    message.error('更新失败')
  } finally {
    confirmLoading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchApiKeyList()
})
</script>

<style scoped lang="less">
.apikey-management {
  .page-header {
    margin-bottom: 24px;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: #1890ff;
    }
    
    p {
      margin: 0;
      color: #666;
      font-size: 14px;
    }
  }

  .api-key-cell {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .masked-key {
      font-family: 'Courier New', monospace;
      color: #666;
    }
    
    .full-key {
      font-family: 'Courier New', monospace;
      color: #333;
      word-break: break-all;
    }
  }

  .detail-content {
    .api-key-display {
      :deep(.ant-input-password) {
        font-family: 'Courier New', monospace;
      }
    }
  }

  :deep(.ant-table-tbody > tr > td) {
    vertical-align: middle;
  }

  :deep(.ant-descriptions-item-label) {
    font-weight: 600;
    background-color: #fafafa;
  }
}
</style> 